package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.core.network.safeApiCallVoid
import com.sgcc.nfc.lock.data.remote.api.RegionApi
import com.sgcc.nfc.lock.data.remote.api.RegionRequest
import com.sgcc.nfc.lock.domain.model.Region
import com.sgcc.nfc.lock.domain.repository.RegionRepository
import javax.inject.Inject

class RegionRepositoryImpl @Inject constructor(
    private val regionApi: RegionApi
) : RegionRepository {

    override suspend fun getRegionTree(): NetworkResult<List<Region>> {
        val response = safeApiCall { regionApi.getRegionTree() }
        return when (response) {
            is NetworkResult.Success -> NetworkResult.Success(response.data.map { it.toDomain() })
            is NetworkResult.Error -> response
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun getRegionChildren(parentId: Long?): NetworkResult<List<Region>> {
        val response = safeApiCall { regionApi.getChildren(parentId) }
        return when (response) {
            is NetworkResult.Success -> NetworkResult.Success(response.data.map { it.toDomain() })
            is NetworkResult.Error -> response
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun createRegion(params: RegionRepository.CreateRegionParams): NetworkResult<Unit> {
        return safeApiCallVoid {
            regionApi.createRegion(
                RegionRequest(
                    regionName = params.regionName,
                    regionType = params.regionType,
                    parentId = params.parentId
                )
            )
        }
    }

    override suspend fun updateRegion(params: RegionRepository.UpdateRegionParams): NetworkResult<Unit> {
        return safeApiCallVoid {
            regionApi.updateRegion(
                params.regionId,
                RegionRequest(
                    regionName = params.regionName,
                    regionType = params.regionType,
                    parentId = params.parentId
                )
            )
        }
    }

    override suspend fun deleteRegion(regionId: Long): NetworkResult<Unit> {
        return safeApiCallVoid { regionApi.deleteRegion(regionId) }
    }
}
